import Watcher from "./Watcher.js"

export default class{
    constructor(el,vue){
        //vue实例
        this.$vue = vue;
        // console.log("vue",vue);
        //挂载点
        this.$el = document.querySelector(el);
        if(this.$el){
            let  $fragment = this.node2Fragment(this.$el)
            this.compile($fragment);
            this.$el.appendChild($fragment);
        }
    }

    node2Fragment(el){
        var fragment = document.createDocumentFragment();
        var child;
        //所有DOM节点进入fragment
        while(child = el.firstChild){
            fragment.appendChild(child)
        }
        return fragment;
    }

    compile(el){
        var childNodes = el.childNodes;
        var self =this;
        var reg = /\{\{(.*)\}\}/
        childNodes.forEach((node)=>{
            var text  = node.textContent;
            if(node.nodeType === 1){
                self.compileElement(node)
            }
            else if(node.nodeType === 3){
                if(reg.test(text)){
                    let name = (text.match(reg))[1]
                    // console.log("name",name);
                    self.compileText(node,name)
                }
            }
        })
    }

    compileElement(node){
       var self =this;
       var nodeAttrs = node.attributes;
       console.log("nodeAttrs",nodeAttrs);
       [].slice.call(nodeAttrs).forEach((attr)=>{
            var name = attr.name;
            var value = attr.value;
            var dir = name.substring(2);
            if(name.indexOf('v-')===0){
                if(dir === "model"){
                    new Watcher(self.$vue,value,value=>{
                        node.value = value;
                    })
                    var v = self.getVueVal(self.$vue,value)
                    //初始化
                    node.value = v;
                    node.addEventListener('input',(e)=>{
                        var newVal = e.target.value;
                        self.setVueVal(self.$vue,value,newVal)
                    })
                }
            }
       })
    }

    compileText(node,name){
        node.textContent = this.getVueVal(this.$vue,name);
        new Watcher(this.$vue,name,value=>{
            node.textContent = value;
        })
    }

    getVueVal(vue,exp){
        var val = vue;
        exp = exp.split('.')
        exp.forEach((k)=>{
            val = val[k]
            console.log(k,val);
        })
        return val;
    }

    setVueVal(vue,exp,value){
        var val = vue;
        exp = exp.split('.')
        exp.forEach((k,i)=>{
            if(i<exp.length-1){
                val = val[k]
            }
            else{
                val[k] = value
            }
        })
    }
}